import PureContextMenu from './pure-context-menu';
import { IYcContextMenu } from './interface';


export default class YcContextMenu {

    contextMenuInfo: PureContextMenu | null = null;

    _menu: Array<IYcContextMenu.Item> = [];

    _option: IYcContextMenu.Config<PureContextMenu> = {}

    callback: <C extends string>(command: C, evt: MouseEvent) => void = () => { }

    constructor(public el: HTMLElement, menu: Array<IYcContextMenu.Item> = []) {
        this.setMenu(menu)
    };

    init() {
        this.contextMenuInfo = new PureContextMenu(this.el, this._menu, this._option);
        return this;
    }

    show(evt: MouseEvent) {
        if (this.contextMenuInfo) {
            this.contextMenuInfo.oncontextmenu(evt)
        }
        return this;
    }

    $off() {
        if (this.contextMenuInfo) {
            this.contextMenuInfo.off()
        }
        return this;
    }

    $on<T extends string>(fn:(command: T, evt: MouseEvent) => void) {
        this.callback = fn as typeof this.callback
        return this;
    }

    toMenu(menu: Array<IYcContextMenu.Item> = []): Array<IYcContextMenu.Item> {
        return menu.map(item => {
            return item === '-' ? item : {
                label: item.label,
                html: item.html,
                command: item.command,
                children: this.toMenu(item.children),
                disabled: item.disabled,
                callback: ((e: MouseEvent) => {
                    const cb = item.callback || this.callback;
                    cb?.(item.command, e);
                })
            }
        })
    }

    setMenu(menu: Array<IYcContextMenu.Item | '-'> = [], option: IYcContextMenu.Config<PureContextMenu> = {}) {
        this._menu = this.toMenu(menu)
        this._option = option
        return this.$off().init();
    }

}